<script lang="ts" setup>
import type { FormInstance } from 'ant-design-vue'
import { cloneDeep } from 'lodash'
import type { InventoryModel } from '@/api/inventory/inventory-list.ts'
import { createInventoryType } from "@/api/inventory/inventory-list.ts";
import {notification} from "ant-design-vue";

const emit = defineEmits(['cancel', 'ok'])

const isUpdate = ref(false)

const visible = ref(false)

const title = computed(() => {
  return isUpdate.value ? '编辑' : '新增'
})

const formRef = ref<FormInstance>()

const formData = ref<InventoryModel>({
  typeName: '',
  typeDescription: '',
  parentTypeId: 0,
  unit: '',

})

const labelCol = { style: { width: '100px' } }
const wrapperCol = { span: 24 }

function open(record?: InventoryModel) {
  visible.value = true
  isUpdate.value = !!record?.typeId
  formData.value = cloneDeep(record) ?? {
    typeName: '',
    typeDescription: '',
    parentTypeId: 0,
    unit: '',
  }
}

async function handleOk() {

  try {
    await formRef.value?.validate()
    // 如果是编辑，则进入编辑调用接口
    if (isUpdate.value){
      //TODO 待补充
      notification.error({
        message: '暂未开发',
        duration: 3,
      })
      visible.value = false
    }else {
      console.log(formData.value);
      // 进入新增接口
      const res = await createInventoryType(formData.value)
      if (res.code == 200){
        notification.success({
          message: '添加成功',
          duration: 3,
        })
        visible.value = false
      }else {
        notification.error({
          message: res.msg,
          duration: 3,
        })
      }
    }
  }
  catch (errorInfo) {
    console.log('Form Validate Failed:', errorInfo)
  }
}

function handleCancel() {
  formRef.value?.resetFields()
  emit('cancel')
}

defineExpose({
  open,
})
</script>

<template>
  <a-modal v-model:open="visible" :title="title" @ok="handleOk" @cancel="handleCancel">
    <a-form ref="formRef" :model="formData" class="w-full" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item name="typeName" label="类型名称" :rules="[{ required: true, message: '请输入仓库类型名称' }]">
        <a-input v-model:value="formData.typeName" :maxlength="50" placeholder="请输入仓库类型名称" />
      </a-form-item>
      <a-form-item name="typeDescription" label="类型描述" :rules="[{ required: true, message: '请输入仓库类型描述' }]">
        <a-input v-model:value="formData.typeDescription" :maxlength="50" placeholder="请输入仓库类型描述" />
      </a-form-item>
      <a-form-item name="unit" label="类型单位" :rules="[{ required: true, message: '请输入仓库类型单位' }]">
        <a-input v-model:value="formData.unit" :maxlength="50" placeholder="请输入仓库类型单位" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
